package com.example.gfsquadwebviewproject.log;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.example.gfsquadwebviewproject.data.Constant;
import com.example.gfsquadwebviewproject.util.PreferencesUtils;
import com.example.gfsquadwebviewproject.util.TimeUtils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class WriteFileLog {

    Context context;
    Constant constant;
    File myDir ;

    public WriteFileLog(Context context) {
        this.context = context;
        myDir = new File(Environment.getExternalStorageDirectory().getPath()
                + "/"+ constant.appName+"_sc");
    }

    public void writeLog(String message) {
        writeLog("log", message+"   "+TimeUtils.getDate_Time());
    }

    public void writeLog(String filename, String message) {
        if (!myDir.exists()) {
            Log.d("Context","创建文件失败");
            if (!myDir.mkdirs()) {
                return;
            }
        }
        File file = new File(myDir, filename + ".txt");
        BufferedWriter fout;
        try {
            fout = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file, true),"UTF-8"));
            fout.write(message + "\n");
            fout.close();
            //保存日志时间超过两天则返回ture，然后删除日志文件

            if(PreferencesUtils.getString(context,"clearFileTime")==null){
                PreferencesUtils.putString(context, "clearFileTime", TimeUtils.getDate_Time());
            }
            else {

                try{
                    SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                    DEFAULT_DATE_FORMAT.parse(PreferencesUtils.getString(context,"clearFileTime"));
                }
                catch (Exception e){
                    PreferencesUtils.putString(context, "clearFileTime", TimeUtils.getDate_Time());//更新时间
                }

                if(TimeUtils.timeDifference(PreferencesUtils.getString(context,"clearFileTime"))){
                    file.delete();//删除文件
                    PreferencesUtils.putString(context, "clearFileTime", TimeUtils.getDate_Time());//删除后更新时间
                }
            }

        }
        catch (IOException e) {
            e.printStackTrace();
            Log.d("Context","删除文件出错："+e);
        }
    }



}
